package org.tea.mapper.util;

import cn.hutool.core.lang.Assert;
import org.apache.ibatis.builder.annotation.ProviderContext;
import org.apache.ibatis.logging.Log;
import org.apache.ibatis.logging.LogFactory;

import java.util.List;

/**
 *@author lxh
 */
public class BaseSelectMapperProvider
        extends MapperHelper {

    private final static Log log = LogFactory.getLog(BaseSelectMapperProvider.class);

    public String selectByPrimaryKey(Object primaryKey, ProviderContext providerContext) {
        log.debug(String.format("primary key: %s, providerContext: %s", primaryKey, providerContext));
        Class<?> mapperType = providerContext.getMapperType();
        Class<?> entityType = parseActualEntityType(mapperType);
        List<String> columnNameList = parseColumns(entityType);
        List<String> primayKeyList = parsePrimaryKeyColumns(entityType);
        String tableName = parseTableName(entityType);

        Assert.notEmpty(primayKeyList);
        StringBuilder sqlBuilder = new StringBuilder();
        sqlBuilder.append("SELECT ").append(String.join(", ", columnNameList)).append("\n")
                .append("FROM ").append(tableName).append("\n")
                .append(" WHERE ").append(primayKeyList.get(0))
                    .append(" = '").append(primaryKey).append("'");
        log.trace(String.format("selectByPrimaryKey sql: %s", sqlBuilder));
        return sqlBuilder.toString();
    }

    public String selectByCondition(Object param, ProviderContext providerContext) {
        Class<?> mapperType = providerContext.getMapperType();
        Class<?> entityType = parseActualEntityType(mapperType);
        List<String> columnList = parseColumns(entityType);
        String tableName = parseTableName(entityType);

        StringBuilder sqlBuilder = new StringBuilder();
        sqlBuilder.append("<script>").append("\n")
                .append("SELECT ").append(String.join(", ", columnList)).append("\n")
                .append("FROM ").append(tableName).append("\n")
                .append("<where>").append("\n")
                .append(buildWhereCondition(entityType))
                .append("</where>").append("\n")
                .append("</script>");

        log.trace(String.format("selectByCondition sql: %s", sqlBuilder));
        return sqlBuilder.toString();
    }
}
